
package com.putao.album.share;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.base.BaseActivity;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

/**
 * Created by jidongdong on 15/3/5.
 */
public class ShareTools {
    /**
     * 微博微博分享接口实例
     */
    public IWeiboShareAPI mWeiboShareAPI = null;
    public IWXAPI mWXAPIFactory = null;
    public Tencent mTencent;
    private QzoneShare mQzoneShare;
    private String mPhotoUrl, mWebUrl;
    private Activity mActivity;
    private String mShareTitle;
    private String mShareDescription;
    private String mAge;

    public ShareTools(Activity activity) {
        mActivity = activity;
//        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mActivity, PuTaoConstants.WEIBO_APP_KEY);
//        mWeiboShareAPI.registerApp();

        mWXAPIFactory = WXAPIFactory.createWXAPI(mActivity, PuTaoConstants.WEIXIN_APP_KEY);
        mWXAPIFactory.registerApp(PuTaoConstants.WEIXIN_APP_KEY);

        if (mTencent == null) {
            mTencent = Tencent.createInstance(PuTaoConstants.QQ_APP_ID, mActivity.getApplicationContext());
        }
        mQzoneShare = new QzoneShare(mActivity, mTencent.getQQToken());


    }

    public void initWeiboShareApi() {
        Loger.i("initWeiboShareApi:");
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mActivity, PuTaoConstants.WEIBO_APP_KEY);
        mWeiboShareAPI.registerApp();
    }


    public ShareTools(Activity activity, String photoUrl, String age) {
        mActivity = activity;
        mAge = age;

        mPhotoUrl = photoUrl;
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mActivity, PuTaoConstants.WEIBO_APP_KEY);
        mWeiboShareAPI.registerApp();

        mWXAPIFactory = WXAPIFactory.createWXAPI(mActivity, PuTaoConstants.WEIXIN_APP_KEY);
        mWXAPIFactory.registerApp(PuTaoConstants.WEIXIN_APP_KEY);

        if (mTencent == null) {
            mTencent = Tencent.createInstance(PuTaoConstants.QQ_APP_ID, mActivity.getApplicationContext());
        }
        mQzoneShare = new QzoneShare(mActivity, mTencent.getQQToken());
        init();

    }

    public ShareTools(Activity activity, String photoUrl, String webUrl, String age) {
        mActivity = activity;
        mAge = age;
        mPhotoUrl = photoUrl;
        mWebUrl = webUrl;
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mActivity, PuTaoConstants.WEIBO_APP_KEY);
        mWeiboShareAPI.registerApp();
        mWXAPIFactory = WXAPIFactory.createWXAPI(mActivity, PuTaoConstants.WEIXIN_APP_KEY);
        mWXAPIFactory.registerApp(PuTaoConstants.WEIXIN_APP_KEY);
        if (mTencent == null) {
            mTencent = Tencent.createInstance(PuTaoConstants.QQ_APP_ID, mActivity.getApplicationContext());
        }
        mQzoneShare = new QzoneShare(mActivity, mTencent.getQQToken());
        init();
    }

    private void init() {
        mShareTitle = CommonUtils.getBabyName() + mAge + "的照片";
        mShareDescription = CommonUtils.getBabyName() + "是不是灰常么么哒";
    }

    //QZone分享
    public void doShareToQzone() {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, mShareTitle);// 必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, mShareDescription);// 选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://putao.im/forum.php");// 必填
        // 分享的图片, 以ArrayList<String>的类型传入，以便支持多张图片（注：图片最多支持9张图片，多余的图片会被丢弃）。
        ArrayList<String> imageUrls = new ArrayList<String>();
        if (mPhotoUrl != null && !mPhotoUrl.equals("")) {
            imageUrls.add(mPhotoUrl);
        }

        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        mQzoneShare.shareToQzone(mActivity, params, new IUiListener() {
            @Override
            public void onCancel() {
                Toast.makeText(mActivity, "取消分享", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Object arg0) {
                Toast.makeText(mActivity, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(UiError arg0) {

            }
        });
    }


    // QQZone分享------------
    public void doShareWebToQzone() {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, mShareTitle);// 必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, mShareDescription);// 选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, mWebUrl);// 必填
        // 分享的图片, 以ArrayList<String>的类型传入，以便支持多张图片（注：图片最多支持9张图片，多余的图片会被丢弃）。
        ArrayList<String> imageUrls = new ArrayList<String>();
        if (mPhotoUrl != null && !mPhotoUrl.equals("")) {
            imageUrls.add(mPhotoUrl);
        }
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        mQzoneShare.shareToQzone(mActivity, params, new IUiListener() {
            @Override
            public void onCancel() {
                Toast.makeText(mActivity, "取消分享", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Object arg0) {
                Toast.makeText(mActivity, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(UiError arg0) {
                Toast.makeText(mActivity, "分享错误", Toast.LENGTH_SHORT).show();
            }
        });
    }


    //QQ分享

    /**
     * private void onClickShare() {
     * final Bundle params = new Bundle();
     * params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
     * params.putString(QQShare.SHARE_TO_QQ_TITLE, "要分享的标题");
     * params.putString(QQShare.SHARE_TO_QQ_SUMMARY,  "要分享的摘要");
     * params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,  "http://www.qq.com/news/1.html");
     * params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
     * params.putString(QQShare.SHARE_TO_QQ_APP_NAME,  "测试应用222222");
     * params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
     * mTencent.shareToQQ(MainActivity.this, params, new BaseUiListener());
     * }
     */

//    public void doShareToQQ() {
//        Bundle params = new Bundle();
//        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
//        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, APP_NAME);
//        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
//        mTencent.shareToQQ(mActivity, params, new IUiListener() {
//            @Override
//            public void onCancel() {
//                ((BaseActivity)mActivity).showToast("取消邀请");
//            }
//
//            @Override
//            public void onComplete(Object arg0) {
//                ((BaseActivity)mActivity).showToast("邀请成功");
//            }
//
//            @Override
//            public void onError(UiError arg0) {
//                ((BaseActivity)mActivity).showToast("邀请错误");
//            }
//        });
//    }
    //通过QQ邀请
    public void doInviteByQQ(String invite_content) {
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "邀请亲友");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, invite_content);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, PuTaoConstants.QQ_INVITE_URL);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, CommonUtils.getCurBabyIconUrl());
        try {
            mTencent.shareToQQ(mActivity, params, new IUiListener() {
                @Override
                public void onCancel() {
                    ((BaseActivity) mActivity).showToast("取消邀请");
                }

                @Override
                public void onComplete(Object arg0) {
                    ((BaseActivity) mActivity).showToast("邀请成功");
                }

                @Override
                public void onError(UiError arg0) {
                    ((BaseActivity) mActivity).showToast("邀请错误");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过微信邀请
     *
     * @param invite_body
     */
    public void doInviteByWeiXin(String invite_body) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = PuTaoConstants.QQ_INVITE_URL;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "亲友邀请";
        msg.description = invite_body;
        Bitmap bmp = ImageLoader.getInstance().loadImageSync(CommonUtils.getCurBabyIconUrl());
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, (int) ((float) bmp.getHeight() / (float) bmp.getWidth() * THUMB_SIZE), true);
        msg.thumbData = bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        mWXAPIFactory.sendReq(req);
    }

    // 微博分享------------
    public void doShareToWeibo() {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();// 初始化微博的分享消息
        weiboMessage.textObject = getTextObj();
        weiboMessage.imageObject = getImageObj();
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        mWeiboShareAPI.sendRequest(mActivity, request); // 发送请求消息到微博,唤起微博分享界面
    }


    //
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = " ";
        return textObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bmp = ImageLoader.getInstance().loadImageSync(mPhotoUrl);
        imageObject.setImageObject(bmp);
        return imageObject;
    }


    public void doShareWebToWeibo() {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();// 初始化微博的分享消息
        weiboMessage.textObject = getTextObj();
        weiboMessage.mediaObject = getWebpageObj();
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        mWeiboShareAPI.sendRequest(mActivity, request); // 发送请求消息到微博,唤起微博分享界面
    }

    // 微信分享------------
    private static final int THUMB_SIZE = 150;
    Bitmap scaledThumb;

    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        try {
            mediaObject.identify = Utility.generateGUID();
            mediaObject.title = mShareTitle;
            mediaObject.description = mShareDescription;
            // 设置 Bitmap 类型的图片到视频对象里
            Bitmap bmp = ImageLoader.getInstance().loadImageSync(mPhotoUrl);
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, (int) ((float) bmp.getHeight() / (float) bmp.getWidth() * THUMB_SIZE), true);
            mediaObject.setThumbImage(thumbBmp);
            mediaObject.actionUrl = mWebUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaObject;
    }

    // 微信分享------------

    public void sendWebToWeixin(boolean isTimelineCb) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = mWebUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = mShareTitle;
        msg.description = mShareDescription;
        Bitmap bmp = ImageLoader.getInstance().loadImageSync(mPhotoUrl);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, (int) ((float) bmp.getHeight() / (float) bmp.getWidth() * THUMB_SIZE), true);
        msg.thumbData = bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimelineCb ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        mWXAPIFactory.sendReq(req);
    }


    public void sendBitmapToWeixin(boolean isTimelineCb) {
        Bitmap bmp = ImageLoader.getInstance().loadImageSync(mPhotoUrl);
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, (int) ((float) bmp.getHeight() / (float) bmp.getWidth() * THUMB_SIZE), true);
        msg.thumbData = bmpToByteArray(thumbBmp, true); // 设置缩略图
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = isTimelineCb ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        mWXAPIFactory.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int quality = 100;
        bmp.compress(Bitmap.CompressFormat.JPEG, quality, output);
        byte[] result = output.toByteArray();
        while (result.length / 1024 > 20) { // 循环判断如果压缩后图片是否大于30kb,大于继续压缩
            output.reset();// 重置baos即清空baos
            quality -= 10;// 每次都减少10
            bmp.compress(Bitmap.CompressFormat.JPEG, quality, output);// 这里压缩options%，把压缩后的数据存放到baos中
            result = output.toByteArray();
        }
        if (needRecycle) {
            bmp.recycle();
        }
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
